import { useRouteQuery } from '@vueuse/router'
import { watch, ref } from 'vue'

export default function useYear() {
  const defaultYear = useRouteQuery('year', '', {
    transform: (val) => Number(val),
  })

  const curYear = new Date().getFullYear()
  const prevFiveYear = curYear - 5

  const generatorYearOptions = () => {
    const options = []
    for (let i = curYear; i >= prevFiveYear; i--) {
      options.push({
        label: i + '年',
        value: i,
      })
    }
    return options
  }

  const year = ref(defaultYear.value ? defaultYear?.value : curYear)

  const yearOptions = generatorYearOptions()

  watch(year, (val) => {
    window.location.href = `${window.location.href.split('?')[0]}?year=${val}`
  })

  return {
    yearOptions,
    year,
  }
}
